<template>
	<div class="chat">
		<div class="top">

		</div>
		<div class="chatTop">
			<ol class="ol" id="ol">

			</ol>
		</div>
		<div class="bottom">
			<el-form ref="form" :model="formDate" label-width="80px">
				<el-form-item label="发送弹幕:">
					<el-input v-model="formDate.content" style="width: 200px;" @keyup.enter.native="submit(formDate.content)"
					 placeholder="请输入内容"></el-input>
					<el-button type="primary" size="small" style="margin-left: 20px;" @click="submit(formDate.content)">主要按钮</el-button>
				</el-form-item>

			</el-form>
		</div>

	</div>
</template>

<script>
	export default {
		name: 'douyuChat',
		data: () => ({
			formDate: {},
			ws: new WebSocket('ws://localhost:8001/connectWebSocket/001')
		}),
		updated: function() {

		},
		created: function() {
			// `this` 指向 vm 实例
			console.log('a is: ' + this.a)
			this.websocket();
		},
		methods: {
			submit(val) {
				// this.websocketonMessage(val);
				this.formDate.content = "";
				this.ws.send(val);
			},
			websocketonMessage(val) {
				if (val) {
					//根据id寻找元素
					const ol = document.getElementById("ol");
					//创建li元素
					var li = document.createElement("li");
					//添加li元素内容为输入框内容
					li.innerText = val;
					//添加元素
					ol.appendChild(li);
					//一直滚动到底部。滚动条
					this.$nextTick(() => {
						let chatTop = document.getElementsByClassName("chatTop");
						chatTop[0].scrollTop = chatTop[0].scrollHeight;
					});
				}
			},
			websocket() {
				const that = this;
				this.ws.onopen = function() {
					console.log("<li>客户端已连接</li>")
				}
				this.ws.onmessage = function(evt) {
					that.websocketonMessage(evt.data)
				}
				this.ws.onclose = function() {
					console.log("<li>客户端已断开连接</li>")
				};
				this.ws.onerror = function(evt) {
					that.websocketonMessage(evt.data)
				};
			}
		}
	}
</script>

<style scoped>
	.chat {
		height: 700px;
		background-color: #693d39;
	}

	.top {
		height: 100px;
	}

	.chatTop {
		height: 500px;
		background-color: #edfff9;
		overflow: auto;
	}

	.chatTop .ol {
		width: 30%;
		left: 20px;
		position: relative;
		list-style-type: none;
	}

	.bottom {
		position: absolute;
		bottom: 0px;
		width: 30%;
	}
</style>
